//
// Created by whg on 2025-06-01.
//

#include "pyString.hpp"
#include "runtime/global.hpp"
#include <string.h>

PyString::PyString(const char* c) {
    _length = strlen(c);
    _value = new char[_length];
    strcpy(_value, c);
    setKlass(StringKlass::getInstance());
}

PyString::PyString(const char* c, const int length) {
    _length = length;
    _value = new char[_length];
    for(int i=0;i<_length;i++){
        _value[i] = c[i];
    }
    setKlass(StringKlass::getInstance());
}

StringKlass* StringKlass::instance = nullptr;

StringKlass* StringKlass::getInstance() {
    if(instance == nullptr){
        instance = new StringKlass();
    }
    return instance;
}

void StringKlass::print(PyObject *obj) {
    PyString* strObj = (PyString*)obj;
    assert(strObj->klass() == this);
    for(int i=0; i<strObj->length();i++){
        putchar(strObj->value()[i]);
    }
}

PyObject *StringKlass::equal(PyObject *x, PyObject *y) {
    if(x->klass() != y->klass()){
        return Global::PyFalse;
    }
    PyString* sx = (PyString*)x;
    PyString* sy = (PyString*)y;

    assert(sx->klass() == this);
    assert(sy->klass() == this);

    if (sx->length() != sy->length()){
        return Global::PyFalse;
    }

    for (int i = 0; i < sx->length(); i++) {
        if (sx->value()[i] != sy->value()[i]){
            return Global::PyFalse;
        }
    }

    return Global::PyTrue;
}

PyObject *StringKlass::len(PyObject *obj) {
    PyString* strObj = (PyString*)obj;
    assert(strObj->klass() == this);
    return new PyInteger(strObj->length());
}

PyObject* upper(ObjList args){
    PyObject* arg0 = args->get(0);
    assert(arg0->klass() == StringKlass::getInstance());

    PyString* strObj = (PyString*)arg0;
    int length = strObj->length();
    if(length <= 0){
        return Global::PyNone;
    }

    char* v = new char[length];
    char c;
    for(int i=0;i<length;i++){
        c = strObj->value()[i];
        if(c >= 'a' && c <= 'z'){
            v[i] = c - 0x20;
        }else{
            v[i] = c;
        }
    }

    PyString* s = new PyString(v, length);
    delete[] v;
    return s;
}
